home *** CD-ROM | disk | FTP | other *** search
- Path: charnel.ecst.csuchico.edu!mcelroy
- From: mcelroy@ecst.csuchico.edu (James Robert McElroy)
- Newsgroups: comp.lang.c++
- Subject: Re: overloaded operator question
- Date: 19 Jan 1996 18:12:48 GMT
- Organization: California State University, Chico
- Message-ID: <4domv0$hfk@charnel.ecst.csuchico.edu>
- References: <4dmin1$160@noc2.drexel.edu>
- NNTP-Posting-Host: hairball.ecst.csuchico.edu
-
- In article <4dmin1$160@noc2.drexel.edu>,
- Jonathan Juniman <st918h5w@dunx1.ocs.drexel.edu> wrote:
- >What is wrong with the following declaration:
- >
- >MATRIX.H
- >class Matrix
- > {
- > public:
- > // several other functions here...
- > Matrix Matrix::operator *(Matrix&, Matrix&);
- > }
- >
-
- As has already been noted, when an overloaded binary operator
- is a class function, the left operand is assumed to be an
- object of the class itself. You might look at it like:
-
- Matrix Matrix::operator * (this, Matrix &) { .... }
-
- You can call the overloaded operator using normal function syntax,
- which might also clarify the picture for you:
-
- Matrix foo(2, 4);
- Matrix bar(4, 4);
- Matrix someMatrix(2,4);
-
- someMatrix = foo.operator*(bar);
- // the same as someMatrix = foo + bar;
-
- Just to clean things up a bit, seeing as how you are not altering
- either the left or right operand here, but instead returning a
- new (temporary) matrix as the result of the operation, your
- method declaration should be:
-
- Matrix Matrix::operator * (const Matrix & right) const;
-
- Your method should look something like:
-
- Matrix Matrix::operator * (const Matrix & right) const
- {
- assert(columnDimension == right.rowDimension);
- Matrix temp(rowDimension, right.columnDimension);
-
- // do matrix multiplication here, assigning values
- // to elements of temp. Note that neither the right
- // or left operators are altered.
-
- return temp;
- }
-
-
- --
- Jim McElroy
- Calif. State Univ., Chico
- mcelroy@ecst.csuchico.edu
-